package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "用户端菜品接口")
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @ApiOperation("用户端-根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> list(@RequestParam Integer categoryId) {
        log.info("根据分类查询菜品：{}", categoryId);

        // 优化缓存
        // 先查询Redis中是否有数据,如果有直接返回
        String key = "dish_" + categoryId;
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (dishVOList != null && !dishVOList.isEmpty()) {
            return Result.success(dishVOList);
        }

        // 如果没有,则查询数据库
        List<DishVO> dishVOs = dishService.listEnableDish(categoryId);

        // 将查询到的数据保存到Redis中
        redisTemplate.opsForValue().set(key, dishVOs);

        return Result.success(dishVOs);
    }
}
